<template>
  <div class="work-statistics-panel">
    <div class="panel-header">
      <h2>工作统计</h2>
    </div>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ serviceStats.total }}</div>
            <div class="stat-label">总申请数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ serviceStats.pending }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ serviceStats.inProgress }}</div>
            <div class="stat-label">处理中</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ serviceStats.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <div class="chart-section">
      <h4>最近7天工作统计</h4>
      <div class="chart-container">
        <div ref="chartRef" class="chart" style="width: 100%; height: 400px;"></div>
      </div>
    </div>
    
    <!-- 详细统计表格 -->
    <div class="detailed-stats">
      <h4>详细统计</h4>
      <el-table :data="serviceRequests" v-loading="loadingServices" style="width: 100%" row-key="id">
        <el-table-column prop="id" label="申请ID" width="80" />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="urgencyLevel" label="紧急程度" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row" :type="getUrgencyType(scope.row.urgencyLevel) || 'info'">
              {{ getUrgencyText(scope.row.urgencyLevel) }}
            </el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row" :type="getServiceStatusType(scope.row.status) || 'info'">
              {{ getServiceStatusText(scope.row.status) }}
            </el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="appointmentTime" label="预约时间" width="180" />
        <el-table-column prop="createdAt" label="申请时间" width="180" />
        <el-table-column prop="completedAt" label="完成时间" width="180" />
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { serviceRequestAPI } from '../services/api.js'
import * as echarts from 'echarts'

export default {
  name: 'WorkStatisticsPanel',
  setup() {
    const loadingServices = ref(false)
    const chartRef = ref(null)
    let chartInstance = null
    
    // 数据
    const serviceRequests = ref([])
    
    // 统计数据
    const serviceStats = reactive({
      total: 0,
      pending: 0,
      inProgress: 0,
      completed: 0,
      cancelled: 0,
      urgent: 0
    })
    
    // 获取服务申请
    const loadServiceRequests = async () => {
      loadingServices.value = true
      try {
        const response = await serviceRequestAPI.getAllServiceRequests()
        serviceRequests.value = response.content || response
        updateServiceStats()
      } catch (error) {
        ElMessage.error('加载服务申请列表失败：' + error.message)
      } finally {
        loadingServices.value = false
      }
    }
    
    // 更新服务统计
    const updateServiceStats = () => {
      serviceStats.total = serviceRequests.value.length
      serviceStats.pending = serviceRequests.value.filter(s => s.status === 'PENDING').length
      serviceStats.inProgress = serviceRequests.value.filter(s => s.status === 'IN_PROGRESS').length
      serviceStats.completed = serviceRequests.value.filter(s => s.status === 'COMPLETED').length
      serviceStats.cancelled = serviceRequests.value.filter(s => s.status === 'CANCELLED').length
      serviceStats.urgent = serviceRequests.value.filter(s => s.urgencyLevel === 'URGENT' || s.urgencyLevel === 'VERY_URGENT').length
      
      // 更新图表
      updateChart()
    }
    
    // 获取最近7天的数据
    const getLast7DaysData = () => {
      const today = new Date()
      const last7Days = []
      
      for (let i = 6; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(date.getDate() - i)
        const dateStr = date.toISOString().split('T')[0]
        
        const dayData = {
          date: dateStr,
          pending: 0,
          inProgress: 0,
          completed: 0,
          cancelled: 0
        }
        
        // 统计当天的服务申请
        serviceRequests.value.forEach(service => {
          if (service.createdAt) {
            const serviceDate = new Date(service.createdAt).toISOString().split('T')[0]
            if (serviceDate === dateStr) {
              switch (service.status) {
                case 'PENDING':
                  dayData.pending++
                  break
                case 'IN_PROGRESS':
                  dayData.inProgress++
                  break
                case 'COMPLETED':
                  dayData.completed++
                  break
                case 'CANCELLED':
                  dayData.cancelled++
                  break
              }
            }
          }
        })
        
        last7Days.push(dayData)
      }
      
      return last7Days
    }
    
    // 初始化图表
    const initChart = () => {
      if (!chartRef.value) return
      
      chartInstance = echarts.init(chartRef.value)
      updateChart()
    }
    
    // 更新图表
    const updateChart = () => {
      if (!chartInstance) return
      
      const chartData = getLast7DaysData()
      const dates = chartData.map(item => {
        const date = new Date(item.date)
        const month = date.getMonth() + 1
        const day = date.getDate()
        return `${month}月${day}日`
      })
      
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: '最近7天工作趋势',
          left: 'center',
          top: 20,
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#2c3e50'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 12
          },
          formatter: function(params) {
            let result = `<div style="padding: 8px;"><strong>${params[0].axisValue}</strong><br/>`
            params.forEach(param => {
              result += `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>${param.seriesName}: <strong>${param.value}</strong><br/>`
            })
            result += '</div>'
            return result
          }
        },
        legend: {
          data: ['待处理', '处理中', '已完成', '已取消'],
          top: 60,
          left: 'center',
          itemGap: 30,
          textStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        grid: {
          left: '8%',
          right: '8%',
          bottom: '15%',
          top: '25%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          },
          axisTick: {
            show: true,
            lineStyle: {
              color: '#e0e0e0'
            }
          },
          axisLabel: {
            color: '#666',
            fontSize: 12,
            margin: 12
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#999',
            fontSize: 12,
            formatter: function(value) {
              return Math.floor(value) === value ? value : '';
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f5f5f5',
              type: 'solid',
              width: 1
            }
          }
        },
        series: [
          {
            name: '待处理',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 3,
              color: '#ff9500'
            },
            itemStyle: {
              color: '#ff9500',
              borderColor: '#fff',
              borderWidth: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(255, 149, 0, 0.3)'
                }, {
                  offset: 1, color: 'rgba(255, 149, 0, 0.05)'
                }]
              }
            },
            data: chartData.map(item => item.pending)
          },
          {
            name: '处理中',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 3,
              color: '#007aff'
            },
            itemStyle: {
              color: '#007aff',
              borderColor: '#fff',
              borderWidth: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(0, 122, 255, 0.3)'
                }, {
                  offset: 1, color: 'rgba(0, 122, 255, 0.05)'
                }]
              }
            },
            data: chartData.map(item => item.inProgress)
          },
          {
            name: '已完成',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 3,
              color: '#34c759'
            },
            itemStyle: {
              color: '#34c759',
              borderColor: '#fff',
              borderWidth: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(52, 199, 89, 0.3)'
                }, {
                  offset: 1, color: 'rgba(52, 199, 89, 0.05)'
                }]
              }
            },
            data: chartData.map(item => item.completed)
          },
          {
            name: '已取消',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 3,
              color: '#ff3b30'
            },
            itemStyle: {
              color: '#ff3b30',
              borderColor: '#fff',
              borderWidth: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(255, 59, 48, 0.3)'
                }, {
                  offset: 1, color: 'rgba(255, 59, 48, 0.05)'
                }]
              }
            },
            data: chartData.map(item => item.cancelled)
          }
        ]
      }
      
      chartInstance.setOption(option)
    }
    
    // 获取紧急程度类型
    const getUrgencyType = (urgency) => {
      if (!urgency) return 'info'
      const typeMap = {
        'GENERAL': 'info',
        'URGENT': 'warning',
        'VERY_URGENT': 'danger'
      }
      return typeMap[urgency] || 'info'
    }
    
    // 获取紧急程度文本
    const getUrgencyText = (urgency) => {
      if (!urgency) return '未知'
      const textMap = {
        'GENERAL': '一般',
        'URGENT': '紧急',
        'VERY_URGENT': '非常紧急'
      }
      return textMap[urgency] || '未知'
    }
    
    // 获取服务状态类型
    const getServiceStatusType = (status) => {
      if (!status) return 'info'
      const typeMap = {
        'PENDING': 'warning',
        'IN_PROGRESS': 'primary',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return typeMap[status] || 'info'
    }
    
    // 获取服务状态文本
    const getServiceStatusText = (status) => {
      if (!status) return '未知'
      const textMap = {
        'PENDING': '待处理',
        'IN_PROGRESS': '处理中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return textMap[status] || '未知'
    }
    
    // 组件挂载时加载数据
    onMounted(async () => {
      await loadServiceRequests()
      await nextTick()
      initChart()
    })
    
    return {
      loadingServices,
      chartRef,
      serviceRequests,
      serviceStats,
      getUrgencyType,
      getUrgencyText,
      getServiceStatusType,
      getServiceStatusText
    }
  }
}
</script>

<style scoped>
.work-statistics-panel {
  padding: 20px;
}

.panel-header {
  margin-bottom: 30px;
}

.panel-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.stats-cards {
  margin-bottom: 30px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.chart-section {
  margin-bottom: 30px;
}

.chart-section h4 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.chart-container {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  padding: 24px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.chart {
  border-radius: 12px;
  background: transparent;
}

.detailed-stats {
  margin-top: 30px;
}

.detailed-stats h4 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 15px;
  }
}
</style>
